import fs from 'fs';
import axios from 'axios';
import moment from 'moment';
let token = '';
let token_expire_time = moment();
const username = 'parkingLot';
const password = '8hG3mGV0deqyn6';

let parkInfo = [];
let channelInfo = [];
let needSave = false;

async function login() {
    if (token && moment().isBefore(token_expire_time)) {
       // console.log('token未过期，无需重新登录');
        return true;
    }
    const url = 'https://chub.scsltech.cn/user/login';
    const data = {
        username: username,
        password: password
    };
    const headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json'
    };
    try {
        const response = await axios.post(url, data, { headers: headers });
        console.log('登录成功:', JSON.stringify(response.data));
        token = response.data.data.token;
        token_expire_time = moment(response.data.data.expire_at);
        return true;
    } catch (error) {
        console.error('登录失败:', error.message);
        return false;
    }
}
async function report(park_no, lot, available_lot, plate, is_entrance, image) {
    // console.log('开始向平台上报过车信息',park_no,plate);
    const params = {
        index: park_no,
        max_number: lot,
        available_number: available_lot,
        license_plate: plate,
        is_entrance: is_entrance,
        image: 'data:image/jpeg;base64,' + image
    };
    const loginSuccess = await login();
    if (!loginSuccess) {
        console.log('登录失败 取消上报');
        return;
    }
    const url = 'https://chub.scsltech.cn/parkingLot/gate';
    const headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
    };
   // console.log('token:', token);
    try {
        const response = await axios.post(url, params, { headers: headers });
        delete params.image;
        console.log('上报成功:',` 入参:${JSON.stringify(params)} 出参:${JSON.stringify(response.data)}` );
        return response.data;
    } catch (error) {
        delete params.image;
        console.error('上报失败:', `请求地址:${url}  入参:${JSON.stringify(params)}  错误原因:${error.message}`);
        return error;
    }
}
//从本地文件中读取所有的车场的信息本地文件名 park_info.json
async function loadParkInfo() {
    try {
        const data = fs.readFileSync('park_info.json', 'utf8');
        parkInfo = JSON.parse(data);
    } catch (err) {
        console.error('读取车场信息失败:', err.message);
    }
}
async function saveParkInfo() {
    try {
        fs.writeFileSync('park_info.json', JSON.stringify(parkInfo));
    } catch (err) {
        console.error('保存车场信息失败:', err.message);
    }
}
async function addParkInfo(park_no, lot,available_lot=0) {
    const park = parkInfo.find(x => x.park_no == park_no);
    if (park) {
        park.lot = lot;
        park.available_lot = available_lot;
    } else {
        parkInfo.push({ park_no, lot,available_lot });
    }
    await saveParkInfo();
}
async function removeParkInfo(park_no) {
    const initialLength = parkInfo.length;
    parkInfo = parkInfo.filter(x => x.park_no != park_no);
    if (parkInfo.length === initialLength) {
        console.error('车场信息不存在:', park_no);
    } else {
        await saveParkInfo();
    }
}
async function loadChannelInfo() {
    try {
        const data = fs.readFileSync('channel_info.json', 'utf8');
        channelInfo = JSON.parse(data);
    } catch (err) {
        console.error('读取通道信息失败:', err.message);
    }
}
async function saveChannelInfo() {
    try {
        fs.writeFileSync('channel_info.json', JSON.stringify(channelInfo));
    } catch (err) {
        console.error('保存通道信息失败:', err.message);
    }
}
async function addChannelInfo(park_no,camera_sn , is_entrance) {
    const channel = channelInfo.find(x => x.camera_sn == camera_sn);
    if (channel) {
        channel.park_no = park_no;
        channel.is_entrance = is_entrance;
    } else {
        channelInfo.push({ camera_sn: camera_sn, park_no: park_no, is_entrance: is_entrance });
    }
    await saveChannelInfo();
}
async function removeChannelInfo(camera_sn) {
    const initialLength = channelInfo.length;
    channelInfo = channelInfo.filter(x => x.camera_sn != camera_sn);
    if (channelInfo.length === initialLength) {
        console.error('通道信息不存在:', camera_sn);
    } else {
        await saveChannelInfo();
    }
}
//车辆进出场处理方法
async function plateReport(sn,plate,image){
    console.log('开始上报过车信息',sn,plate);
    const channel = channelInfo.find(x => x.camera_sn == sn);
    if (!channel) {
        console.log('通道信息不存在:', sn,plate);
        return;
    }
    const park = parkInfo.find(x => x.park_no == channel.park_no);
    if (!park) {
        console.log('车场信息不存在:', channel.park_no,plate);    
        return;
    }
    if (channel.is_entrance) {
        park.available_lot--;
    } else {
        park.available_lot++;
    }
    if(needSave==false){
        needSave=true;
    }
    await report(channel.park_no, park.lot, park.available_lot, plate, channel.is_entrance, image);
}
//定时任务，每隔10秒保存车场信息
async function saveTask(){
    if(needSave){
        await saveParkInfo();
        needSave=false;
    }
}
function getChannelInfo(){
    return channelInfo;
}
function getParkInfo(){
    return parkInfo;
}
setInterval(saveTask,10000);
export default { addParkInfo, removeParkInfo, addChannelInfo, removeChannelInfo, plateReport, loadParkInfo, loadChannelInfo,getChannelInfo,getParkInfo };
loadChannelInfo();
loadParkInfo();